/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    void traversal(TreeNode *cur, vector<int> &vec)
    {
        if (cur == nullptr)
        {
            return;
        }

        vec.push_back(cur->val);
        traversal(cur->left, vec);
        traversal(cur->right, vec);
    }

    vector<int> preorderTraversal(TreeNode *root)
    {
        // 1.递归法
        // vector<int> vec;
        // TreeNode * cur = root;
        // traversal(cur, vec);

        // 2.迭代法
        // vector<int> vec;
        // stack<TreeNode *> st;
        // st.push(root);

        // while (!st.empty()){
        //     TreeNode * node = st.top();
        //     st.pop();
        //     if(node != nullptr){
        //         vec.push_back(node->val);
        //         st.push(node->right);
        //         st.push(node->left);
        //     }
        // }

        // 3. 统一迭代法
        vector<int> result;
        stack<pair<TreeNode *, bool>> st;

        if (root)
        {
            st.push(make_pair(root, false));
        }

        while (!st.empty())
        {
            TreeNode *node = st.top().first;
            bool visited = st.top().second;
            st.pop();

            if (visited)
            {
                result.push_back(node->val);
                continue;
            }
            // 中左右
            if (node->right)
            {
                st.push(make_pair(node->right, false));
            }
            if (node->left)
            {
                st.push(make_pair(node->left, false));
            }
            if (node)
            {
                st.push(make_pair(node, true));
            }
        }

        return result;
    }
};